package com.hutu.aop;

import com.hutu.annotation.AuthCheck;
import com.hutu.common.ErrorCode;
import com.hutu.exception.BusinessException;
import com.hutu.model.entity.Account;
import com.hutu.model.enums.AccountRoleEnum;
import com.hutu.properties.JwtProperties;
import com.hutu.service.AccountService;
import com.hutu.utils.UserThreadLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 权限校验 AOP
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private AccountService accountService;


    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        Long userId = UserThreadLocal.get();
        if (Objects.isNull(userId)) {
            return false;
        }
        // 当前登录用户
        Account loginUser = accountService.getById(userId);
        AccountRoleEnum mustRoleEnum = AccountRoleEnum.getEnumByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 必须有该权限才通过
        AccountRoleEnum accountRoleEnum = AccountRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (accountRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 如果被封号，直接拒绝
        if (AccountRoleEnum.BAN.equals(accountRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 必须有管理员权限
        if (AccountRoleEnum.ADMIN.equals(mustRoleEnum)) {
            // 用户没有管理员权限，拒绝
            if (!AccountRoleEnum.ADMIN.equals(accountRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

